<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { useInspectionCheckHook } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "@iconify-icons/ep/delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { useUserStoreHook } from "@/store/modules/user";
import InspectionDetailFormModal from "./inspectionDetail-addForm-modal.vue"; // 引入新增弹窗组件
import EditPen from "@iconify-icons/ep/edit-pen";
import { InspectionCheckDTO } from "@/api/airport/inspection/inspectionCheck";
import AddFill from "@iconify-icons/ri/add-circle-line";
import { getInspectionInfoApi, UpdateInspectionCommand, updateInspectionApi } from "@/api/airport/inspection/inspection";
import dayjs from "dayjs";
import {useRoute} from "vue-router";
import {CommonUtils} from "@/utils/common";
import {ElMessage, ElMessageBox} from "element-plus";
import {message} from "@/utils/message";
import OnlineCheckModal from "./OnlineCheckModal.vue";
import InspectionCheckDetailModal from "@/views/airport/inspection/inspectionCheck/inspectionCheck-detail-modal.vue";
import { getUserListApi, UserDTO } from '@/api/system/user';

defineOptions({
  name: "inspectionDetailMobile"
});

const inspectionId = ref("");
const route = useRoute();
inspectionId.value = route.query.inspectionId as string;

const {
  searchFormParams,
  pageLoading,
  columns,
  dataList,
  pagination,
  defaultSort,
  multipleSelection,
  onSearch,
  resetForm,
  onSortChanged,
  exportAllExcel,
  getInspectionCheckList,
  handleDelete,
  handleBulkDelete,
  deptTree
} = useInspectionCheckHook(inspectionId.value); // 传入 .value 获取原始值

const inspectionInfo = ref(null);
const opType = ref<"add" | "update">("add");
const modalVisible = ref(false);
const opRow = ref<InspectionCheckDTO>();
const tableRef = ref();
const approverName = ref(''); // 新增：存储审批人姓名

const userStore = useUserStoreHook();
const currentUserId = userStore.currentUserInfo.userId;

// 格式化检查级别
const formatInspectionLevel = (inspectionLevel: string) => {
  switch (inspectionLevel) {
    case "1":
      return "公司级";
    case "2":
      return "部门级";
    case "3":
      return "科室级";
    default:
      return inspectionLevel;
  }
};

// 格式化计划日期
const formatPlanDate = (planDate: string) => {
  return dayjs(planDate).format("YYYY-MM-DD");
};

// 格式化检查小组名单
const formatUserNameList = (userNameList: string[]) => {
  if (Array.isArray(userNameList)) {
    return userNameList.join(", ");
  }
  return "";
};

// 定义状态映射对象
const statusMap = {
  '0': '计划待提交',
  '1': '计划待审批',
  '2': '计划已驳回',
  '3': '检查待开始',
  '4': '正在检查',
  '5': '已完成'
};
const detailVisible = ref(false);

function openDetail(row?: InspectionCheckDTO) {
  opRow.value = row;
  detailVisible.value = true;
}


// 格式化状态
const formatStatus = (status: number | undefined) => {
  if (status !== undefined) {
    const statusStr = String(status);
    return statusMap[statusStr] || "未知状态";
  }
  return "未知状态";
};

// 获取检查信息
const fetchInspectionInfo = async () => {
  if (inspectionId.value) {
    try {
      const res = await getInspectionInfoApi(inspectionId.value);
      inspectionInfo.value = res.data;
      // 新增：如果有审批人ID，则使用现有的getUserListApi获取审批人姓名
      if (inspectionInfo.value?.approver) {
        await fetchApproverName(inspectionInfo.value.approver);
      } else {
        approverName.value = '';
      }
    } catch (error) {
      console.error("获取检查信息失败", error);
    }
  }
};

const fetchApproverName = async (userId: number) => {
  try {
    const res = await getUserListApi({ userId: userId });
    // 直接使用返回的数据，避免访问不存在的records属性
    if (res) {
      approverName.value = res.data.rows[0]?.username || '';


    } else {
      approverName.value = '';
    }
  } catch (error) {
    console.error("获取审批人信息失败", error);
    approverName.value = '';
  }
};


onMounted(() => {
  fetchInspectionInfo();
  searchFormParams.inspectionId = Number(inspectionId.value);
  getInspectionCheckList();
});

function openDialog(type: "add" | "update", row?: InspectionCheckDTO) {
  opType.value = type;
  opRow.value = row;
  modalVisible.value = true;
}

// 处理成功事件，刷新表格
const handleModalSuccess = () => {
  fetchInspectionInfo();
  getInspectionCheckList();
};

// 【新增】定义行高和表头高度常量
const ROW_HEIGHT = 40;
const HEADER_HEIGHT = 40;

// 【修改】计算固定为10行数据的表格高度
const tableHeight = computed(() => {
  // 10行数据的高度 + 表头高度 + 额外边距
  return 5 * ROW_HEIGHT + HEADER_HEIGHT + 20;
});


// 提交检查计划
const submitInspection = async () => {
  ElMessageBox.confirm(
    '是否确认提交该检查计划？',
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const updateData: UpdateInspectionCommand = {
        inspectionId: Number(inspectionId.value),
        status: '1',
        // 其他必要字段，根据接口要求补充
        inspectionName: inspectionInfo.value?.inspectionName || '',
        // 可以根据实际情况添加更多字段
      };

      await updateInspectionApi(updateData);
      message("提交成功", {
        type: "success"
      });
      // 刷新检查信息
      await fetchInspectionInfo();
    } catch (error) {
      console.error('提交失败', error);
      message("提交失败，请重试", {
        type: "error"
      });
    }
  }).catch(() => {
    message("取消提交", {
      type: "info"
    });
  });
};

const submitApprove  = async () => {
  ElMessageBox.confirm(
    '是否确认审批该检查计划？',
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {



      const updateData: UpdateInspectionCommand = {
        inspectionId: Number(inspectionId.value),
        status: '3',
        inspectionName: inspectionInfo.value?.inspectionName || '',
        approver: currentUserId,
        suggestion: '同意审批'
      };
      await updateInspectionApi(updateData);
      message("审批成功", {
        type: "success"
      });
      // 刷新检查信息
      await fetchInspectionInfo();
    } catch (error) {
      console.error('提交失败', error);
      message("提交失败，请重试", {
        type: "error"
      });
    }
  }).catch(() => {
    message("取消提交", {
      type: "info"
    });
  });
};

// 确认完成检查
const confirmCompleteInspection = async () => {
  try {
    // 增加检查：判断是否存在未检查的项目
    const hasUncheckedItems = dataList.value.some(item => item.inspectionResult === '0');
    if (hasUncheckedItems) {
      ElMessage.warning('存在未检查的项目，请先完成所有检查项');
      return;
    }
    await ElMessageBox.confirm(
      '是否确认完成并提交检查？',
      '系统提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const inspectionId1 = Number(inspectionId.value);
    const endTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    const updateData: UpdateInspectionCommand = {
      inspectionId: inspectionId1,
      status: '5',
      endTime,
      // 检查名称为必填字段，需从已有数据获取
      inspectionName: '123'
    };

    // 调用更新检查计划接口
    await updateInspectionApi(updateData);
    ElMessage.success('检查已完成并提交');
    // 刷新列表
    handleModalSuccess();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('完成检查失败');
      console.error('完成检查失败', error);
    }
  }
};


// 定义驳回审批函数
const rejectApproval = async () => {
  try {
    const { value: suggestion } = await ElMessageBox.prompt(
      '请输入驳回意见',
      '驳回审批',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入驳回意见',
        inputValidator: (value) => {
          if (!value) {
            return '驳回意见不能为空';
          }
          return true;
        }
      }
    );

    if (suggestion) {
      const updateData: UpdateInspectionCommand = {
        inspectionId: Number(inspectionId.value),
        status: '2',
        inspectionName: inspectionInfo.value?.inspectionName || '',
        approver: currentUserId,
        suggestion
      };

      await updateInspectionApi(updateData);
      message("驳回成功", {
        type: "success"
      });
      // 刷新检查信息
      await fetchInspectionInfo();
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('驳回失败', error);
      message("驳回失败，请重试", {
        type: "error"
      });
    }
  }
};


// 提交判断
const isStatusZero = computed(() => inspectionInfo.value?.status === '0'||inspectionInfo.value?.status === '2');
const isStatus1 = computed(() => inspectionInfo.value?.status === '1');
const isStatus34 = computed(() => inspectionInfo.value?.status === '3'||inspectionInfo.value?.status === '4');

// 新增格式化检查来源
const formatInspectionSource = (inspectionSource: string) => {
  const inspectionSourceOptions = [
    { label: "年度检查", value: "1" },
    { label: "临时检查", value: "2" }
  ];
  const option = inspectionSourceOptions.find(item => item.value === inspectionSource);
  return option ? option.label : inspectionSource;
};

// 新增格式化检查周期
const formatInspectionPeriod = (inspectionPeriod: string) => {
  const inspectionPeriodOptions = [
    { label: "年度", value: "1" },
    { label: "月度", value: "2" },
    { label: "无", value: "3" }
  ];
  const option = inspectionPeriodOptions.find(item => item.value === inspectionPeriod);
  return option ? option.label : inspectionPeriod;
};

// 新增弹窗相关变量
const onlineCheckModalVisible = ref(false);
const onlineCheckRow = ref<InspectionCheckDTO>();

// 新增判断状态为 3 的计算属性
const isStatusThree = computed(() => inspectionInfo.value?.status === '3'||inspectionInfo.value?.status === '4');

// 打开在线检查弹窗
function openOnlineCheckDialog(row: InspectionCheckDTO) {
  onlineCheckRow.value = row;
  onlineCheckModalVisible.value = true;
}
</script>

<template>
  <div>
    <div class="inspection-info">
      <div v-if="inspectionInfo" class="info-container">
        <div class="info-row">
          <p><span>检查计划名称:</span> {{ inspectionInfo.inspectionName }}</p>
          <p><span>计划日期:</span> {{ formatPlanDate(inspectionInfo.planDate) }}</p>
          <p><span>检查来源:</span> {{ formatInspectionSource(inspectionInfo.inspectionSource) }}</p>
          <p><span>检查小组名单:</span> {{ formatUserNameList(inspectionInfo.userNameList) }}</p>
        </div>


        <div v-if="inspectionInfo.status === '2'" class="info-row">
          <p>
            <span>驳回意见:</span>
            <span style="color: red; font-weight: bold;">{{ inspectionInfo.suggestion }}</span>
          </p>
        </div>
      </div>
    </div>

    <PureTableBar title="检查项列表" :columns="columns" @refresh="onSearch">
      <template #buttons>
        <el-button
          type="primary"
          @click="submitInspection"
          v-if="isStatusZero"
        >
          提交
        </el-button>
        <el-button
          type="success"
          @click="confirmCompleteInspection"
          v-if="isStatus34"
        >
          完成检查
        </el-button>
        <el-button
          type="primary"
          @click="submitApprove"
          v-if="isStatus1"
        >
          通过审批
        </el-button>

        <el-button
          type="danger"
          @click="rejectApproval"
          v-if="isStatus1"
        >
          驳回审批
        </el-button>

        <el-button
          v-if="isStatusZero"
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog('add')"
        >
          新增检查项
        </el-button>
        <el-button
          v-if="isStatusZero"
          type="danger"
          :icon="useRenderIcon(Delete)"
          @click="handleBulkDelete(tableRef)"
        >
          批量删除
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="pageLoading"
          :size="size"
          :data="dataList"
          :columns="dynamicColumns"
          :default-sort="defaultSort"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="getInspectionCheckList"
          @page-current-change="getInspectionCheckList"
          @sort-change="onSortChanged"
          @selection-change="
            rows => (multipleSelection = rows.map(item => item.inspectionCheckId))
          "
          :height="tableHeight"
        >

          <template  #operation="{ row }">
            <el-popconfirm
              :title="`是否确认删除编号为${row.inspectionCheckId}的这个检查项`"
              @confirm="handleDelete(row)"
              v-if="isStatusZero"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="danger"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
            <el-button
              :link="row.inspectionResult === '0'"
              :type="row.inspectionResult === '0' ? 'primary' : 'danger'"
              :size="size"
              v-if="isStatus34"
              @click="openOnlineCheckDialog(row)"
            >
              {{ row.inspectionResult === '0' ? '在线检查' : '重新检查' }}
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <online-check-modal
      v-model="onlineCheckModalVisible"
      :row="onlineCheckRow"
      :dept-tree="deptTree"
      type="update"
      @success="handleModalSuccess"

    />

    <inspectionDetail-form-modal
      v-model="modalVisible"
      :type="opType"
      :row="opRow"
      @success="handleModalSuccess"
    />

    <inspectionCheck-detail-modal
      v-model="detailVisible"
      :row="opRow"
      @success="handleModalSuccess"
    />
  </div>


</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}


.inspection-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  /* 新增：确保在移动设备上占满宽度 */
  width: 100%;
  box-sizing: border-box;
}

.info-container {
  display: flex;
  flex-direction: column;
  gap: 0; // 行间距
}

.info-row {
  display: flex;
  gap: 20px; // 列间距
  /* 新增：在移动设备上改为垂直排列 */
  @media (max-width: 768px) {
    flex-direction: column;
    gap: 8px;
  }
}

.info-row p {
  margin: 8px 0;
  display: flex;
  align-items: center;
  flex: 1; // 让每个 p 元素平均分配宽度
  /* 新增：缩小字体大小适配手机 */
  font-size: 14px;
  @media (max-width: 768px) {
    font-size: 13px;
    margin: 4px 0;
  }
}

.info-row p span {
  width: 120px;
  font-weight: bold;
  /* 新增：缩小标签字体 */
  font-size: 14px;
  @media (max-width: 768px) {
    width: 120px;
    font-size: 13px;
  }
}

:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
.main-content {
  margin: 7px !important;
}
</style>
